package com.dmzapp.api.servlet;

import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.dmzapp.api.service.RedisAndDBService;
import com.dmzapp.api.util.Constant;
import com.dmzapp.api.vo.IncomeRecord;

/**
 * Servlet implementation class for Servlet: UserInOutDetailHandler
 * 
 */
public class UserInDetailHandler extends com.dmzapp.api.servlet.DMZSerlvet {
    static final long serialVersionUID = 1L;
    private ObjectMapper mapper = new ObjectMapper();

    /*
     * (non-Java-doc)
     * 
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */
    public UserInDetailHandler() {
        super();
    }

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {

        try {
            String username = (String) request.getAttribute("u");
            int start = Integer.valueOf(request.getParameter("start"));
            Map<String, Object> responseMap = new HashMap<String, Object>();

            List<IncomeRecord> incomelist = RedisAndDBService.getUserInfomelist(username);

            if (incomelist != null && !incomelist.isEmpty()) {
                int total = incomelist.size();
                Collections.sort(incomelist);
                int end = total - start < Constant.APP_LIST_PAGE_SIZE ? total : start + Constant.APP_LIST_PAGE_SIZE;
                List<IncomeRecord> sub = incomelist.subList(start, end);
                
                responseMap.put("incomelist", sub);
                responseMap.put("listSize", total);
                responseMap.put("amount", RedisAndDBService.getUserAmount(username));
                responseMap.put("rest", RedisAndDBService.getUserRest(username));
                responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());
                mapper.writeValue(response.getWriter(), responseMap);
            } else {
                mapper.writeValue(response.getWriter(), "nothing");
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}